"""
命令行界面
提供用户交互式操作
"""

import argparse
import logging
import sys
from pathlib import Path

from ..core.video_manager import VideoManager


def setup_logging():
    """设置日志配置"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.StreamHandler(sys.stdout),
            logging.FileHandler('python4video.log', encoding='utf-8')
        ]
    )


def main():
    """主函数"""
    setup_logging()
    logger = logging.getLogger(__name__)
    
    parser = argparse.ArgumentParser(description='AI视频生成与剪映集成工具')
    parser.add_argument('--config', '-c', default='config.yaml', 
                       help='配置文件路径')
    
    subparsers = parser.add_subparsers(dest='command', help='子命令')
    
    # 生成视频命令
    generate_parser = subparsers.add_parser('generate', help='生成AI视频')
    generate_parser.add_argument('--text', '-t', required=True, 
                               help='视频文案内容')
    generate_parser.add_argument('--project-name', '-p', 
                               help='剪映项目名称')
    generate_parser.add_argument('--output', '-o', 
                               help='视频输出路径')
    
    # 列出草稿命令
    list_parser = subparsers.add_parser('list-drafts', help='列出剪映草稿')
    
    # 清理命令
    cleanup_parser = subparsers.add_parser('cleanup', help='清理临时文件')
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return
    
    try:
        manager = VideoManager(args.config)
        
        if args.command == 'generate':
            result = manager.generate_and_import_sync(args.text, args.project_name)
            
            if result['success']:
                print("✅ 视频生成并导入成功！")
                print(f"📁 视频文件: {result['video_path']}")
                print(f"📁 剪映草稿: {result['draft_path']}")
            else:
                print("❌ 操作失败:")
                print(f"错误: {result['error']}")
                
        elif args.command == 'list-drafts':
            drafts = manager.list_jianying_drafts()
            if drafts:
                print("📋 剪映草稿列表:")
                for draft in drafts:
                    print(f"  - {draft['name']} (ID: {draft['id']})")
            else:
                print("📭 未找到剪映草稿")
                
        elif args.command == 'cleanup':
            manager.cleanup_temp_files()
            print("🧹 临时文件清理完成")
            
    except Exception as e:
        logger.error(f"程序执行失败: {e}")
        print(f"❌ 程序执行失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()